﻿using UnityEditor;

/// <summary>
/// 开发工具管理类
/// </summary>
[InitializeOnLoad]
public class DevelopManager : AssetPostprocessor
{
    private const string RELOAD_ASSEMBLIES_KEY = "LockReloadAssemblies";
    private static bool m_IsLockReload;

    public static DevelopScriptableObject DevelopScriptableObject
        => AssetDatabase.LoadAssetAtPath<DevelopScriptableObject>("Assets/Editor/DevelopManager/DevelopScriptableObject.asset");

    static DevelopManager()
    {
        if (Config.Default.IsEditorListeners)
        {
            EditorApplication.update += Update;
            Logger.Log("开启编辑器监测".RichTextGreenColor());
        }
    }

    static void Update()
    {

    }

    [UnityEditor.Callbacks.DidReloadScripts]
    static void CompiledInvoke()
    {
        Logger.Log("编辑器编译完成".RichTextGreenColor());

        m_IsLockReload = EditorPrefs.GetBool(RELOAD_ASSEMBLIES_KEY, false);
        SetLockReloadAssemblies(m_IsLockReload);

        UIVariableGenerator.AddUIFormScript();
    }


    /// <summary>
    /// 设置是否锁定自动编译程序集
    /// </summary>
    [MenuItem(Constant.EditorMenu.MENU_LOCK_RELOAD_ASSEMBLIES_PATH, priority = Constant.EditorMenu.LOCK_RELOAD_ASSEMBLIES_PRIORITY)]
    static void SetLockReloadAssemblies()
    {
        m_IsLockReload = EditorPrefs.GetBool(RELOAD_ASSEMBLIES_KEY, false);
        if (m_IsLockReload)
        {
            SetLockReloadAssemblies(!m_IsLockReload);
        }
        else
        {
            if (EditorUtility.DisplayDialog("提示", "是否锁定“重新加载程序集”功能 \n\n锁定后无法重新加载程序集,\n也不会触发脚本编译。",
                "确认锁定",
                "取消"))
            {
                SetLockReloadAssemblies(!m_IsLockReload);
            }
        }
    }

    static void SetLockReloadAssemblies(bool isLock)
    {
        m_IsLockReload = isLock;
        if (isLock)
        {
            EditorApplication.LockReloadAssemblies();
            Logger.LogWarning("重新加载程序集已锁定。".RichTextGreenColor());
        }
        else
        {
            EditorApplication.UnlockReloadAssemblies();
            Logger.LogWarning("重新加载程序集功能已解锁。".RichTextGreenColor());
        }
        EditorPrefs.SetBool(RELOAD_ASSEMBLIES_KEY, isLock);
        Menu.SetChecked(Constant.EditorMenu.MENU_LOCK_RELOAD_ASSEMBLIES_PATH, isLock);
    }

    /// <summary>
    /// 编译程序集
    /// </summary>
    [MenuItem(Constant.EditorMenu.MENU_RELOAD_ASSEMBLIES_PATH, priority = Constant.EditorMenu.RELOAD_ASSEMBLIES_PRIORITY)]
    static void ReloadAssemblies()
    {
        Logger.Log("手动重新加载程序集……");
        EditorApplication.UnlockReloadAssemblies();
        EditorUtility.RequestScriptReload();
        AssetDatabase.Refresh();
    }
}
